const { exec } = require('child_process');
const SPLIT = '------------------------------';

function fetchCode() {
  return new Promise((resolve, reject) => {
    exec(`git fetch origin api`, (error, stdout, stderr) => {
      if (error) {
        console.error(`执行 fetch 出错: ${error}`);
        return reject(error);
      }
      console.log(`fetch`);
      console.log(`stdout: ${stdout}`);
      console.error(`stderr: ${stderr}`);
      console.error(SPLIT);
      resolve();
    });
  });
}

function mergeCode() {
  return new Promise((resolve, reject) => {
    exec(`git merge origin/api`, (error, stdout, stderr) => {
      if (error) {
        console.error(`执行 merge 出错: ${error}`);
        return reject(error);
      }
      console.log(`merge`);
      console.log(`stdout: ${stdout}`);
      console.error(`stderr: ${stderr}`);
      console.error(SPLIT);
      resolve();
    });
  });
}

function buildCode() {
  return new Promise((resolve, reject) => {
    exec(`npm run build`, (error, stdout, stderr) => {
      if (error) {
        console.error(`执行 build 出错: ${error}`);
        return reject(error);
      }
      console.log(`build`);
      console.log(`stdout: ${stdout}`);
      console.error(`stderr: ${stderr}`);
      console.error(SPLIT);
      resolve();
    });
  });
}

console.error(SPLIT);
fetchCode()
  .then(() => {
    mergeCode().then(() => {
      buildCode();
    });
  })
  .catch(error => console.error(error));
